(function() {
    'use strict';

    /**
     * @ngdoc service
     * @name webApp.myrest
     * @description
     * # myrest
     * Service in the webApp.
     */
    angular.module('webApp')
        .service('dataService', ['$rootScope', '$http', '$q', 'cacheService', 'sessionService', 'authService', 'ERP_CONFIG', 'md5', 'moment', '$filter', 'helper', '$timeout', 'base64',
            function($rootScope, $http, $q, cacheService, sessionService, authService, ERP_CONFIG, md5, moment, $filter, helper, $timeout, base64) {
                var dataService = {
                    reject: reject,
                    promise: promise,
                    resolve: resolve,
                    userCurrentGet: userCurrentGet,
                    login: login,
                    logout: logout,
                    tpl: tpl,
                    getToken: getToken,
                    removeAllCache: removeAllCache,
                    removeDataCache: removeDataCache,
                    buyerWxlogin: buyerWxlogin,
                    buyerbasicinfoGet: buyerbasicinfoGet,
                    h5hdGetOne: h5hdGetOne,
                    h5hddetlAdd: h5hddetlAdd,
                    h5hddetailOne: h5hddetailOne,
                    jssdkSignGet: jssdkSignGet,
                    cardSignGet: cardSignGet
                }
                return dataService;

                function cardSignGet(data) {
                    if (data.content) {
                        data.content = JSON.stringify(data.content);
                    }
                    return requestApi("/rest/v1/php/cardsign/get", data).then(function(result) {
                        return result;
                    });
                }

                //h5活动的
                function jssdkSignGet(app_id, url) {
                    var data = {
                        app_id: app_id,
                        url: url,
                    }
                    return requestApi("/rest/v1/jssdk/sign/get", data).then(function(result) {
                        return result;
                    });
                }
                //h5活动的
                function h5hdGetOne(h5hd_id) {
                    var data = {
                        content: { h5hd_id: h5hd_id }
                    }
                    data.content = angular.toJson(data.content);
                    return requestApi("/rest/v1/php/dhf/h5hd/get", data).then(function(result) {
                        if (!result.Msg) {
                            return result.h5hd_list[0];
                        } else {
                            return reject("没有查到活动");
                        }
                    });
                }
                //h5详情的
                function h5hddetailOne(data) {
                    data.content = angular.toJson(data.content);
                    return requestApi("/rest/v1/php/dhf/h5hd/details/get", data).then(function(result) {
                        if (!result.Msg) {
                            return result.h5hd_detail_list[0];
                        } else {
                            return reject("没有查到活动");
                        }
                    });
                }

                //h5活动的
                function h5hddetlAdd(data) {
                    data.content = angular.toJson(data.content);
                    return requestApi("/rest/v1/php/dhf/h5hd/details/add", data).then(function(result) {
                        return result
                    });
                }

                //基于公众号的顾客登录
                function buyerWxlogin(appid, code, all) {
                    var data = {
                        app_id: appid,
                        code: code,
                        all: all,
                    }
                    return requestApi("/public/buyer/wxlogin", data).then(function(result) {
                        if (result.token) {
                            /*****************************
                             * Role的字段，数字类型： 1 表示买家 2 表示卖家 3 表示供应商 4 表示管理者
                             ******************************/

                            var decoded = jwt_decode(result.token);

                            console.error("result.token:----", decoded);

                            sessionService.put("token", result.token);
                            sessionService.put("tokenUser", decoded.CurrentUser);
                            return userCurrentGet();
                        } else {
                            return result;
                        }
                    });
                }

                //q获取买家用户微信信息
                function buyerbasicinfoGet(member_id, open_id) {
                    if (member_id) {
                        var data = { member_id: member_id };
                    } else if (open_id) {
                        var data = { open_id: open_id };
                    } else {
                        return reject("参数不正确");
                    }
                    return requestApi("/rest/v1/buyer/basicinfo/get", data).then(function(result) {
                        return result;
                    });
                }

                //获取用户登录信息
                function userCurrentGet(getCache) {
                    // console.log("asdds", getCache);
                    if (getCache) {
                        var cacheInfo = sessionService.get('currentUserInfo');
                        if (cacheInfo) {
                            // console.error("11111111")
                            return resolve(cacheInfo);
                        }
                    }
                    var tokenUser = sessionService.get("tokenUser");
                    if (!tokenUser) {
                        login();
                        // console.error("2222222")

                        return reject();
                    }
                    // console.error("tokenUser", tokenUser)

                    return buyerbasicinfoGet(tokenUser.Id).then(function(result) {
                        // console.log("currentUserInfo", result)
                        if (result && result.nick_name) {
                            var user = _.extend(result, tokenUser);
                        } else {
                            var user = tokenUser;
                        }
                        user.member_id = tokenUser.Id;

                        sessionService.put('currentUserInfo', user);
                        // console.error("3333333")

                        return sessionService.get('currentUserInfo');
                    });
                }

                //登录动作
                function login(name, pwd, company_id) {
                    $rootScope.$broadcast("event:auth-loginRequired");
                }

                //退出
                function logout() {
                    var tokenUser = sessionService.get("tokenUser") || {};
                    return requestApi('/rest/buyer/user/logout').then(function(result) {
                        sessionService.removeAll();
                        return result;
                    });
                }

                //加载模板
                function tpl(url) {
                    return $http.get(url).then(function(result) {
                        //return 
                        if (result && result.data) {
                            return result.data;
                        } else {
                            return 'none template';
                        }
                    });
                }

                function getToken(cb) {
                    var token = sessionService.get('token');
                    if (token) {
                        cb(token);
                    } else {
                        $rootScope.login();
                    }
                }

                //清空所有缓存
                function removeAllCache() {
                    cacheService.destroy();
                    sessionService.removeAll();
                    return resolve();
                }

                //清空API请求缓存
                function removeDataCache() {
                    cacheService.destroy();
                    return resolve();
                }

                /************************* end *****************************************************/

                //通用请求
                function requestApi(path, data, ttl, method) {
                    //开发模式下，ttl设置为0
                    ttl = 0;
                    // console.log("api请求1：", ERP_CONFIG.eprUrl + path, data, angular.toJson(data));
                    data = data ? data : {};

                    if (data.start_created) {
                        data.start_created = toStdTime(data.start_created);
                    }

                    if (data.end_created) {
                        data.end_created = toStdTime(data.end_created);
                    }

                    var token = sessionService.get('token');
                    if (token) {
                        // data.token = token;
                    }

                    if ("page_size" in data) {
                        if (!_.isNumber(data.page_size)) {
                            data.page_size = 10;
                        }
                    }

                    if ("page_no" in data) {
                        if (!_.isNumber(data.page_no)) {
                            data.page_no = 1;
                        }
                    }


                    //缓存
                    if (ttl) {
                        var questKey = md5.createHash(path + angular.toJson(data));
                        var cacheVal = cacheService.get(questKey, ttl);
                        if (cacheVal) {
                            //console.log("api命中缓存：", questKey, path, data, cacheVal);
                            return returnData(cacheVal);
                        } else {
                            //console.log("没有查到缓存：", cacheVal);
                        }
                    }

                    //组装query字段
                    if (data.query && !_.isObject(data.query)) {
                        return helper.message("query不是object：" + data.query, "error", 15);
                    }

                    if (data.query && _.isObject(data.query)) {
                        var queryTmp = [];
                        _.map(data.query, function(v, k) {
                            queryTmp.push(k + ":" + v);
                        });
                        data.query = queryTmp.join(",");
                    }

                    var headers = null;
                    if (!method) {
                        var httpMethod = "POST";
                        var trueUrl = ERP_CONFIG.eprUrl + path;
                        var params = null;
                        var requestData = data;
                        if (token) {
                            requestData.token = token;
                        }
                    } else {
                        var httpMethod = "GET";
                        var trueUrl = ERP_CONFIG.eprUrl + path;
                        var params = data;
                        var requestData = null;
                        if (token) {
                            //console.error("-------", path, path.indexOf("/rest/v1/"));
                            if (path.indexOf("/rest/v1/") === 0) {
                                headers = { Authorization: token };
                                //console.error("-------", headers);
                            }
                        }
                    }

                    //console.log("bbbbbbb", trueUrl, requestData);
                    return $http({
                        method: httpMethod,
                        url: trueUrl,
                        params: params,
                        data: requestData,
                        headers: headers,
                    }).then(function(res) {
                        //console.log("resresresres", res);
                        var result = clone(res.data);
                        if (ttl) {
                            // console.log("存入缓存：", path, questKey, data, result);
                            if (result && !result.Err) {
                                cacheService.set(questKey, result, ttl);
                            }
                        }
                        console.log("api请求2：", httpMethod, trueUrl, params, requestData, headers, "返回：", JSON.parse(angular.toJson(result)));

                        return returnData(result);
                    }, function(response) {
                        console.error("response", response);
                        if (response.status == 403) {
                            // if (path.indexOf("/add") != -1 || path.indexOf("/update") != -1 || path.indexOf("/delete") != -1) {
                            helper.message("缺少权限：" + path, "error", 15);
                            // }
                            return {
                                Err: 1,
                                Msg: "Need permission:" + path
                            };
                        } else {
                            console.log("http error:", response);
                            return {
                                Err: 1,
                                Msg: "error...."
                            };
                        }
                    });
                }

                function buildQuery(obj, prefix) {
                    var str = [];
                    for (var p in obj) {
                        if (obj.hasOwnProperty(p)) {
                            var k = prefix ? prefix + "[" + p + "]" : p,
                                v = obj[p];
                            str.push(typeof v == "object" ?
                                buildQuery(v, k) :
                                encodeURIComponent(k) + "=" + encodeURIComponent(v));
                        }
                    }
                    return str.join("&");
                }

                //总返回数据
                function returnData(data) {
                    var timeKeys = ['created_at', 'update_at', 'updated_at', 'pre_in_time', 'produce_time', 'expire_time', 'pay_time', 'start_date', 'end_date', 'seller_agree_time', 'start_time', 'end_time', 'huodong_start_time', 'huodong_end_time', 'sign_time', , 'upload_time', 'publish_time', 'subaduit_time', 'order_cycle_start', 'order_cycle_end', 'created_time'];
                    if (_.isArray(data) || _.isObject(data)) {
                        _.map(data, function(v, k) {
                            if (_.isString(v) && timeKeys.indexOf(k) != -1) {
                                data[k] = currentTime(v);
                            }

                            if (_.isArray(v) || _.isObject(v)) {
                                _.map(v, function(v1, k1) {
                                    if (_.isString(v1) && timeKeys.indexOf(k1) != -1) {
                                        data[k][k1] = currentTime(v1);
                                    }

                                    if (_.isArray(v1) || _.isObject(v1)) {
                                        _.map(v1, function(v2, k2) {
                                            if (_.isString(v2) && timeKeys.indexOf(k2) != -1) {
                                                data[k][k1][k2] = currentTime(v2);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                    return resolve(data);
                }

                //把标准时间变成当地时间
                function currentTime(utcTime) {
                    // return moment.tz(utcTime, "Etc/UTC").tz(moment.tz.guess()).format("YYYY-MM-DD HH:mm:ss");
                    var timezone;
                    if (window.localStorage.timezone) {
                        timezone = window.localStorage.timezone;
                    } else {
                        timezone = moment.tz.guess();
                    }

                    return moment.tz(utcTime, "Etc/UTC").tz(timezone).format("YYYY-MM-DD HH:mm:ss");
                }

                //把当地变成标准时间
                function toStdTime(x) {
                    return $filter('stdTime')(x);
                }

                //返回promis
                function resolve(res) {
                    // console.log("resolve:", res);
                    var def = $q.defer();
                    def.resolve(res);
                    return def.promise;
                }

                function reject(res) {
                    console.log("reject:", res);
                    return $q.reject(res);
                }

                function promise() {
                    return $q.when(true);
                }

            }
        ]);
})();